package com.xm.service.impl;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.xm.context.BaseContext;
import com.xm.domain.dto.SetmealDTO;
import com.xm.domain.dto.SetmealPageQueryDTO;
import com.xm.domain.po.Category;
import com.xm.domain.po.Employee;
import com.xm.domain.po.Setmeal;
import com.xm.domain.po.SetmealDish;
import com.xm.domain.vo.SetmealVO;
import com.xm.mapper.SetmealMapper;
import com.xm.result.PageResult;
import com.xm.service.SetmealService;
import com.xm.utils.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 套餐 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {


    @Override
    @Transactional
    public void saveWithDish(SetmealDTO setmealDTO) {

        //1 插入套餐
        Setmeal setmeal = BeanUtils.copyBean(setmealDTO, Setmeal.class);
        setmeal.setCreateTime(LocalDateTime.now());
        setmeal.setUpdateTime(LocalDateTime.now());
        setmeal.setStatus(0);

        //1.1 拿到当前商家id,去找到店铺
        Long currentId = BaseContext.getCurrentId();
        Employee employee = Db.lambdaQuery(Employee.class).eq(Employee::getId, currentId).one();
        String shopId = employee.getShopId();
        setmeal.setShopId(shopId);

        save(setmeal);

        //2 将菜品插入到联系表
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();

        setmealDishes.forEach(setmealDish -> setmealDish.setSetmealId(setmeal.getId()));

        Db.saveBatch(setmealDishes);


    }

    @Override
    public PageResult<SetmealVO> pageQuery(SetmealPageQueryDTO setmealPageQueryDTO) {
        //1构建分页条件
        //1.1 分页条件
        Page<Setmeal> page = Page.of(setmealPageQueryDTO.getPageNo(),setmealPageQueryDTO.getPageSize());
        //1.2 排序条件 基本默认根据修改时间降序
        page.addOrder( OrderItem.desc("update_time"));

        //2.分页查询
        //2.1 拿到当前商家id,去找到店铺

        Long currentId = BaseContext.getCurrentId();
        Employee employee = Db.lambdaQuery(Employee.class).eq(Employee::getId, currentId).one();
        String shopId = employee.getShopId();

        Page<Setmeal> p= lambdaQuery()
                .like(setmealPageQueryDTO.getName() != null, Setmeal::getName, setmealPageQueryDTO.getName())
                .eq(setmealPageQueryDTO.getStatus() != null, Setmeal::getStatus,setmealPageQueryDTO.getStatus())
                .eq(setmealPageQueryDTO.getCategoryId() != null,Setmeal::getCategoryId, setmealPageQueryDTO.getCategoryId())
                .eq(Setmeal::getShopId,shopId)
                .page(page);
        //3封装PageResult结果
        PageResult<SetmealVO> pageResult = new PageResult<>();
        //3.1 总条数
        pageResult.setTotal( page.getTotal());

        //3.2 总页数
        pageResult.setPages(page.getSize());
        //3.3 数据
        List<Setmeal> records = p.getRecords();
        if (CollUtil.isEmpty(records)){
            pageResult.setList(Collections.emptyList());
        }


        //将数据放到封装菜品方法
        List<SetmealVO> setmealVOS =setmealWithDish(records);

        // 将分类名称封装到vo
      setmealWithCategoryName(setmealVOS);

        pageResult.setList(setmealVOS);
        return pageResult;
    }


    /**
     * 将数据放到封装菜品方法
     * @param records
     * @return
     */
  public   List<SetmealVO>  setmealWithDish( List<Setmeal> records ){

      List<SetmealVO> setmealVOS = BeanUtils.copyList(records, SetmealVO.class);
      // 将List<Setmeal>里面的Setmeal过滤只保留id
      List<String> ids = records.stream().map(Setmeal::getId).collect(Collectors.toList());
      //根据Setmeal的id查询所有的关联数据
      List<SetmealDish> list = Db.lambdaQuery(SetmealDish.class).in(SetmealDish::getSetmealId, ids).list();
      // 将关联数据根据Setmeal的id相同分组
      Map<String, List<SetmealDish>> collect = list.stream().collect(Collectors.groupingBy(SetmealDish::getSetmealId));
      // 直接遍历List<SetmealVO> setmealVOS 根据里面储存的Setmeal的id去分好组的集合找到自己的关联数据集合
      setmealVOS.forEach(setmealVO ->setmealVO.setSetmealDishes(collect.get(setmealVO.getId().toString())) );

      return setmealVOS;
  }

    // 将分类名称封装到vo
    public  void    setmealWithCategoryName( List<SetmealVO>  setmealVOS){

        List<Long> collect = setmealVOS.stream().map(SetmealVO::getCategoryId).collect(Collectors.toList());
        List<Category> list = Db.lambdaQuery(Category.class).in(Category::getId, collect).list();
        Map<String, Category> collect1 = list.stream().collect(Collectors.toMap(key -> key.getId(), value -> value));
        setmealVOS.forEach(setmealVO -> setmealVO.setCategoryName(collect1.get(setmealVO.getCategoryId().toString()).getName()));


    }
}
